// @ts-nocheck
<!--
 * @Description: 悟空软件
 * @Author: 悟空
 * @Date: 2020-05-26 15:23:33
 * @LastEditTime: 2020-06-29 19:12:07
 * @LastEditors: yang
 -->

<template>
  <el-dialog ref="wkDialog" :visible="visible" :append-to-body="true" :close-on-click-modal="false" :title="title"
    width="700px" @close="handleCancel">
    <el-form ref="deptAddForm" :model="deptAddForm" :rules="rules" :validate-on-rule-change="false"
      label-position="top">
      <el-form-item v-for="(item, index) in tempList" :key="index" :prop="item.field">
        <span slot="label">
          {{ item.name }}
        </span>
        <el-input v-if="item.formType == 'text'" v-model="deptAddForm[item.field]" :maxlength="item.maxlength || 100"
          placeholder="请输入内容" />
        <el-input-number v-else-if="item.formType == 'number'" v-model="deptAddForm[item.field]" :max="99999999"
          :min="0" :disabled="isCompanyType && isPreparationField(item.field)"
        />
        <el-radio-group v-else-if="item.formType == 'radio'" v-model="deptAddForm[item.field]">
          <el-radio @change="changeRadio($event, item)" v-for="set in item.setting" :key="set.value"
            :label="set.value">{{ set.label }}</el-radio>
        </el-radio-group>
        <wk-dep-select v-else-if="item.formType == 'structure'" v-model="deptAddForm[item.field]"
          :props="{ dataType: 'hrm' }" :params="structureParams" style="width: 100%;" radio
          @change="changeDept($event, item)" />
        <!-- <wk-user-select v-else-if="item.formType == 'user'" v-model="deptAddForm[item.field]" :request="item.request"
          :props="{ label: 'employeeName', value: 'employeeId'}" style="width: 100%;"
          radio :key="index"/> -->
        <el-select style="width: 100%;" v-else-if="item.formType == 'user'" v-model="deptAddForm[item.field]" filterable
          @change="changeSelect" placeholder="请选择" :multiple="item.name == '分管领导'" collapse-tags>
          <el-option v-for="o in item.userList" :key="o.employeeId" :label="o.employeeName" :value="o.employeeId">
          </el-option>
        </el-select>
        <el-select v-else-if="item.formType == 'select'" v-model="deptAddForm[item.field]" placeholder="请选择" @change="changeSelect" >
          <el-option v-for="(sItem, sIndex) in item.setting" :key="sIndex" :label="sItem.label" :value="sItem.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button v-debounce="handleConfirm" type="primary">保存</el-button>
      <el-button @click.native="handleCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  hrmDeptQueryEmployeeAPI,
  hrmDeptChildrenCountAPI,
  hrmDeptQueryManageEmployeeAPI
} from '@/api/hrm/dept'
import { hrmEmployeeQueryByDeptAPI } from "@/api/hrm/employee";
import { hrmDeptAddDeptAPI, hrmDeptSetDeptAPI } from "@/api/hrm/dept";

import WkUserSelect from "@/components/NewCom/WkUserSelect";
import WkDepSelect from "@/components/NewCom/WkDepSelect";

import ElDialogLoadingMixin from "@/mixins/ElDialogLoading";

export default {
  // 组织操作
  name: "DeptAddDialog",
  components: {
    WkUserSelect,
    WkDepSelect,
  },
  mixins: [ElDialogLoadingMixin],
  props: {
    data: Object,
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      handlerType: "add",
      loading: false,
      deptAddForm: {
        deptType: 1,
      },
      userList: [],
      tempList: [],
    };
  },
  computed: {
    isCompanyType() {
      return this.deptAddForm.deptType === 1;
    },
    title() {
      return this.data ? "编辑组织部门" : "新建组织部门";
    },
    rules() {
      const tempRules = {
        name: {
          required: true,
          message: "请输入",
          trigger: ["blur", "change"],
        },
        code: {
          required: true,
          message: "请输入",
          trigger: ["blur", "change"],
        },
        deptType: {
          required: true,
          message: "请选择",
          trigger: ["blur", "change"],
        },
        // mainEmployeeId: { required: true, message: '请选择', trigger: ['blur', 'change'] },
        // leaderEmployeeId: { required: true, message: '请选择', trigger: ['blur', 'change'] }
      };

      if (!this.data || this.data.parentId !== 0) {
        tempRules["parentId"] = {
          required: true,
          message: "请选择",
          trigger: ["blur", "change"],
        };
      }

      return tempRules;
    },
    structureParams() {
      return this.data
        ? { type: "update", id: this.data.deptId }
        : { type: "tree" };
    },
  },
  watch: {
    visible: {
      async handler(val) {
        if (val) {
          if (this.data) {
            this.handlerType = "update";
            this.deptAddForm = {
              deptType: this.data.deptType,
              code: this.data.code,
              sortId: this.data.sortId,
              orgSector: this.data.orgSector,
              unitProperties: this.data.unitProperties,
              orgType: this.data.orgType,
              sectionChiefPreparation: this.data.sectionChiefPreparation,
              deputySectionChiefPreparation : this.data.deputySectionChiefPreparation,
              directorPreparation : this.data.directorPreparation,
              deputyDirectorPreparation : this.data.deputyDirectorPreparation,
              name: this.data.name,
              mainEmployeeId: this.data.mainEmployeeId ? this.data.mainEmployeeId : '',
              leaderEmployeeId: this.data.leaderEmployeeId ? this.data.leaderEmployeeId.split(',') : '',
              parentId: this.data.parentId,
            };
            if (this.data) {
              this.isShow(this.data.deptId)
              this.changeRadio(this.data.deptType, {field: 'deptType'});
            }
            let list = await this.getUser(this.data ? this.data.deptId : null)
            this.tempList.forEach(o => {
              if (o.name == '分管领导') {
                o.userList = list
                this.$forceUpdate()
              }
              if (o.name == '组织负责人') {
                o.userList = list
                this.$forceUpdate()
              }
            })
          } else {
            this.handlerType = "add";
            // 重置状态
            this.deptAddForm = {
              deptType: 1,
            };
          }

          this.$nextTick(() => {
            if (this.$refs.deptAddForm) {
              this.$refs.deptAddForm.clearValidate();
            }
          });
        }
      },
      immediate: true,
    },
  },
  async created() {
    this.tempList = [
      {
        name: "组织部门名称",
        field: "name",
        formType: "text",
        maxlength: 60,
        setting: [],
      },
      // {
      //   name: "组织编码",
      //   field: "code",
      //   maxlength: 60,
      //   formType: "text",
      //   setting: [],
      // },
      {
        name: "组织类型",
        field: "deptType",
        formType: "radio",
        setting: [
          {
            label: "公司",
            value: 1,
          },
          {
            label: "部门",
            value: 2,
          },
        ],
      },
    ];

    if (!this.data || this.data.parentId !== 0) {
      this.tempList.push({
        name: "上级组织",
        field: "parentId",
        formType: "structure",
        setting: [],
      });
    }

    this.tempList.push(
      {
        name: "组织负责人",
        field: "mainEmployeeId",
        formType: "user",
        request: hrmEmployeeQueryByDeptAPI,
        setting: [],
        userList: []
      },
      {
        name: "分管领导",
        field: "leaderEmployeeId",
        formType: "user",
        request: hrmEmployeeQueryByDeptAPI,
        setting: [],
        userList: []
      },
      {
        name: '机构板块',
        field: 'orgSector',
        formType: 'select',
        setting: [{
          label: '集团总部',
          value: 1
        }, {
          label: '公用事业',
          value: 2
        }, {
          label: '金融投资',
          value: 3
        }, {
          label: '现代农业',
          value: 4
        }, {
          label: '工程地产',
          value: 5
        }, {
          label: '其他板块',
          value: 6
        }
        ]
      },
      {
        name: '单位性质',
        field: 'unitProperties',
        formType: 'select',
        setting: [{
          label: '合并报表企业',
          value: 1
        }, {
          label: '托管企业',
          value: 2
        }, {
          label: '其他',
          value: 0
        }]
      },
      {
        name: '组织性质',
        field: 'orgType',
        formType: 'select',
        setting: [{
          label: '全资',
          value: 1
        }, {
          label: '控股',
          value: 2
        }, {
          label: '参股',
          value: 3
        }, {
          label: '集体所有制',
          value: 4
        }]
      },
      {
        name: '正处编制人数',
        field: 'sectionChiefPreparation',
        formType: 'number',
        setting: []
      },{
        name: '副处编制人数',
        field: 'deputySectionChiefPreparation',
        formType: 'number',
        setting: []
      },{
        name: '正科编制人数',
        field: 'directorPreparation',
        formType: 'number',
        setting: []
      },{
        name: '副科编制人数',
        field: 'deputyDirectorPreparation',
        formType: 'number',
        setting: []
      },
      {
        name: '排序号',
        field: 'sortId',
        formType: 'number',
        setting: []
      }
    );
    this.$forceUpdate()
  },
  methods: {
    isPreparationField(field) {
      const preparationFields = [
        'sectionChiefPreparation',
        'deputySectionChiefPreparation',
        'directorPreparation',
        'deputyDirectorPreparation'
      ];
      return preparationFields.includes(field);
    },
    async changeDept(e, item) {
      if (e.length > 0) {
        this.isShow(e[0])
      } else {
      }
      let list
      list = await this.getUser(e[0])
      this.tempList.forEach(o => {
        if (o.name == '分管领导') {
          o.userList = list
          this.deptAddForm[o.field] = ''
        }
        if (o.name == '组织负责人') {
          o.userList = list
          // if (this.title == '编辑组织部门') {
          //   o.userList = [...o.userList, ...this.userList];
          // }
          this.deptAddForm[o.field] = ''
        }
      })
      this.$forceUpdate()
    },

    changeRadio(e, item) {
      if (item.field == "deptType") {
        if (e == 2) {
          const index1 = this.tempList.findIndex(item => item.name == '机构板块');
          if (index1 !== -1) {
            this.tempList.splice(index1, 1);
            this.deptAddForm.orgSector = null;
            this.deptAddForm.unitProperties = null;
            this.deptAddForm.orgType = null;
          }
          const index2 = this.tempList.findIndex(item => item.name == '单位性质');
          if (index2 !== -1) {
            this.tempList.splice(index2, 1);
          }
        } else if (e == 1) {
          let addIndex = this.tempList.length - 1;
          let manageIndex = this.tempList.findIndex(item => item.name == '分管领导');
          if (manageIndex !== -1) {
            addIndex = manageIndex + 1;
          }
          const index1 = this.tempList.findIndex(item => item.name == '机构板块');
          if (index1 == -1) {
            let data = {
              name: '机构板块',
              field: 'orgSector',
              formType: 'select',
              setting: [{ label: '集团总部', value: 1 }, { label: '公用事业', value: 2 }, {
                label: '金融投资',
                value: 3
              }, { label: '现代农业', value: 4 }, { label: '工程地产', value: 5 }, { label: '其他板块', value: 6 }]
            }
            this.tempList.splice(addIndex, 0, data);
            addIndex++;
          }
          const index2 = this.tempList.findIndex(item => item.name == '单位性质');
          if (index2 == -1) {
            let data = {
              name: '单位性质',
              field: 'unitProperties',
              formType: 'select',
              setting: [{
                label: '合并报表企业',
                value: 1
              }, {
                label: '托管企业',
                value: 2
              }, {
                label: '其他',
                value: 0
              }]
            }
            this.tempList.splice(addIndex, 0, data);
            this.$forceUpdate();
          }
        }
      }
    },
    //是否展示编制人数
    isShow(deptId) {
      if (!deptId || this.handlerType == "add") return;
      hrmDeptChildrenCountAPI(deptId).then(res => {
        if (res.data > 0) {
        } else {
        }
      }).catch(() => { })
    },
    //  获取用户列表
    async getUser(deptId) {
      let data = { deptId: deptId }
      let res = await hrmDeptQueryManageEmployeeAPI(data)
      // res.data.list.forEach(o => { o.employeeId = o.employeeId * 1 })
      return res.data
    },
    /**
     * 取消选择
     */
    handleCancel() {
      this.$emit("update:visible", false);
    },

    /**
     * 点击确定
     */
    handleConfirm() {
      this.$refs.deptAddForm.validate((valid) => {
        if (valid) {
          const params = {};
          params.name = this.deptAddForm.name;
          params.code = this.deptAddForm.code;
          params.sortId = this.deptAddForm.sortId;
          params.orgSector = this.deptAddForm.orgSector;
          params.unitProperties = this.deptAddForm.unitProperties;
          params.orgType = this.deptAddForm.orgType;
          params.deptType = this.deptAddForm.deptType;
          params.parentId = this.deptAddForm.parentId;
          params.mainEmployeeId = this.deptAddForm.mainEmployeeId;
          params.sectionChiefPreparation = this.deptAddForm.sectionChiefPreparation;
          params.deputySectionChiefPreparation = this.deptAddForm.deputySectionChiefPreparation;
          params.directorPreparation = this.deptAddForm.directorPreparation;
          params.deputyDirectorPreparation = this.deptAddForm.deputyDirectorPreparation;
          this.loading = true;
          if (this.data) {
            params.deptId = this.data.deptId;
          }
          const request = this.data ? hrmDeptSetDeptAPI : hrmDeptAddDeptAPI;
          request(params)
            .then((res) => {
              this.loading = false;
              this.$message.success(`${this.title}成功`);
              this.$store.dispatch("GetHrmDeptList");
              this.$emit("success");
              this.handleCancel();
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    changeSelect(e) {
      this.$forceUpdate()
    }
  },
};
</script>

<style lang="scss" scoped>
.el-form {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -23px;

  ::v-deep .el-form-item.is-required .el-form-item__label::before {
    margin-right: 0;
  }
}

.el-form-item {
  flex: 0 0 50%;
  flex-shrink: 0;
  padding: 0 40px;
  padding-bottom: 10px;
  margin-bottom: 4px;

  ::v-deep .el-form-item__label {
    padding: 5px 0;
    line-height: inherit;
    color: $--color-text-primary;
  }

  ::v-deep .el-form-item__error {
    padding-top: 2px;
  }
}
</style>
